export const formatDate = (date) => {
  if (!(date instanceof Date)) {
    return "Invalid Date"
  }
  const year = date.getFullYear();
  const monthWithLeadingZero1 = date.getMonth() < 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
  const monthWithLeadingZero2 = date.getMonth() + 1
  const day1 = date.getDate() < 9 ? '0' + date.getDate() : date.getDate()
  const day2 = date.getDate()
  const yearTime = `${year}-${monthWithLeadingZero1}-${day1}`
  const time = `${monthWithLeadingZero2}-${day2}`
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
  let name =  weekdays[date.getDay()]
  return { yearTime, time, name }
}

export const getFourDays = () => {
  const today = new Date();
  const fourDays = [];
  for (let i = 0; i < 4; i++) {
    const nextDay = new Date(today)
    nextDay.setDate(today.getDate() + i)
    let formattedDate = {
      time: formatDate(nextDay).time,
      yearTime: formatDate(nextDay).yearTime,
      name: ''
    }
    if (i === 0) {
      formattedDate.name = '今天'
    } else if (i === 1) {
      formattedDate.name = '明天'
    } else {
      const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
      formattedDate.name = weekdays[nextDay.getDay()]
    }
    fourDays.push(formattedDate)
  }
  return fourDays
}


const isDateRangeExceeds5Days = (startDate, endDate) => {
  // 获取日期之间的毫秒数差值
  const timeDifference = Math.abs(endDate.getTime() - startDate.getTime());

  // 计算天数
  const daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));

  // 判断是否超过 5 天
  return daysDifference > 5;
}

export const getRangeDays = (startDate, endDate) => {
  const minStartDate = new Date(startDate)
  const today = new Date()
  let currentDate = new Date(startDate)
  if (minStartDate.getTime() < today.getTime()) {
    currentDate = today
  }
  const formatDate = (date) => {
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}-${day}`
  };
  const result = []
  const tomorrow = new Date()
  tomorrow.setDate(tomorrow.getDate() + 1)
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  while (result.length < 4 && currentDate <= new Date(endDate)) {
    let formattedDate = {
      time: formatDate(currentDate),
      yearTime: currentDate.toLocaleDateString(),
      name: weekdays[currentDate.getDay()]
    }
    if (currentDate.toDateString() === (new Date()).toDateString()) {
      formattedDate.name = '今天'
    }
    if (currentDate.toDateString() === tomorrow.toDateString()) {
      formattedDate.name = '明天'
    }
    result.push(formattedDate)
    currentDate.setDate(currentDate.getDate() + 1)
  }
  return {
    list: result,
    more: isDateRangeExceeds5Days(startDate, endDate)
  }
}


export const getDistance = (distance) => {
  let number = Number(distance)
  // if (number < 1000) {
  //   return `${number}米`
  // }
  // number = number / 1000
  return `${number}公里`
}

export const maskIdNumber = (idNumber) => {
  // 验证输入是否为18位身份证号码
  if (idNumber?.length !== 18 || !/^\d{17}[\dXx]$/.test(idNumber)) {
    return "无效的身份证号码"
  }
  // 将除前3位和后3位以外的字符替换为*
  const maskedIdNumber = idNumber?.substring(0, 3) + "*".repeat(12) + idNumber?.substring(15, 18)
  return maskedIdNumber
}

export function maskPhoneNumber(phoneNumber) {
  // 检查输入是否合法
  if (typeof phoneNumber !== 'string' || phoneNumber.length !== 11) {
    return phoneNumber
  }

  // 提取前三位和后四位
  const firstThree = phoneNumber.substring(0, 3);
  const lastFour = phoneNumber.substring(7, 11);

  // 用星号替代中间的数字
  const maskedMiddle = '****';

  // 拼接并返回结果
  const maskedPhoneNumber = firstThree + maskedMiddle + lastFour;
  return maskedPhoneNumber;
}

export const isValidPhoneNumber = (phoneNumber) => {
  const phonePattern = /^1[3-9]\d{9}$/
  return  phonePattern.test(phoneNumber)
}

export  function extractAddressInfo(address) {
  const regex = /(.+?[省市自治区])(.+?[市区])(.+?[街道镇乡])/;
  const match = address?.match(regex);

  if (match && match.length === 4) {
    // const city = match[1];
    const district = match[2];
    const street = match[3];

    return `${district}${street}`;
  } else {
    return address; // 地址格式不匹配或信息不完整，返回null或其他适当的值
  }
}


// {arr: pandaList, key: id, county: countyActive}
export const filterAndRemoveDuplicates = (data) => {
  const {arr, key, county} = data
  const uniqueObjects = {}
  let result = []

  for (const obj of arr) {
    if (!uniqueObjects[obj[key]]) {
      uniqueObjects[obj.id] = true
      result.push(obj)
    }
  }
  if (county) {
    result = result.filter((item) => {
      return item.address.includes(county.label)
    })
    // label address
  }
  return result
}

export const getSalesVolume = (salesVolume) => {
  let number = +salesVolume
  if (number >= 100) {
    let str = number.toString()
    return `${str[0]}${Array(str.length - 1).fill(0).join('')}+`
  }
  return number
}


export const addWidthToImages = (htmlString) => {
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = htmlString
  const images = tempDiv.querySelectorAll('img')
  images.forEach(image => {
    image.style.width = '100%'
  })
  const updatedHtmlString = tempDiv.innerHTML
  return updatedHtmlString;
}


